package xyz.naoyu.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;

/**
 * @author yWieLoc
 * @date 2022/3/15 20:33
 */
public class InfoPack {


    /**
     * 将sql结果转为JSON数组String
     * @param rsSet sql结果集
     * @return  相应JSON(Array)
     * @throws SQLException
     */
    public static String resToJSON(ResultSet rsSet) throws SQLException {
        List users = new ArrayList<>();
        try {
            ResultSetMetaData md = rsSet.getMetaData();//获取键名
            int columnCount =  md.getColumnCount();//获取行的数量
            while (rsSet.next()) {
                Map rowData = new HashMap();//声明Map
                for (int i = 1; i <= columnCount; i++) {
                    rowData.put(md.getColumnName(i), rsSet.getObject(i));//获取键名及值
                }
                users.add(rowData);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.toJSONString(users);
    }


    public static  String toSearch(Set<String> set) {
        if(set.isEmpty())   return null;
        StringBuilder res = new StringBuilder();

        for(Iterator<String> it = set.iterator();;) {
            res.append('"').append(it.next()).append('"').append(" = ?");
            if(it.hasNext())    res.append(" and ");
            else break;
        }
        return res.toString();
    }

    /**
     * 将键值打包成带引号的逗号隔开
     * @param set   给定的键值集
     * @return res
     */

    public static String toList(Set<String> set) {
        if(set.isEmpty())   return null;
        StringBuilder res = new StringBuilder();
        for(Iterator<String> it = set.iterator();;) {
            res.append("\"").append(it.next()).append("\"");

            if(it.hasNext())    res.append(",");
            else break;
        }
        return res.toString();
    }

    /**
     * 将json的键集转化尾sql语句后半段
     * @param set   给定的键值集
     * @return  适应sql语句的       --例: "(xx,xx)values(?,?)"
     */
    public static String toFill(Set<String> set,String method){
        String res = "(" + toList(set) + ")";
        StringBuilder val = new StringBuilder("(");

        if(set.isEmpty())   return null;
        for(Iterator<String> it = set.iterator();;) {
            it.next();
            val.append("?");
            if(it.hasNext()) {
                val.append(",");
            } else {
                 val.append(")");
                break;
            }
        }
        return res+ " " + method + " "+ val;
    }


}
